package com.ymatou.iapi.trading.useranalysis.testcase;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.trading.operate.parameter.OrderItemVo;
import com.ymatou.iapi.trading.operate.parameter.PlaceOrderResp;
import com.ymatou.iapi.trading.operate.parameter.PlaceOrderService;
import com.ymatou.iapi.trading.operate.parameter.req.PlaceOrderReq;
import com.ymatou.iapi.trading.ordersync.service.SyncVerifyService;
import com.ymatou.query.seller.trading.api.service.OrderCreate;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.database.model.mongo.query.FirstPaidOrder;
import com.ymttest.database.mongo.UserAnalysisMongoWapper;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;

/**
 * 获取买家首单信息
 */
@TestSuite
@Ignore
//接口废弃
public class Ts_ChangeBuyerFirstOrder {

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("获取买家在指定卖家下的订单统计信息接口");
	}

	@Before
	public void caseUp() {
	}

	@AfterClass
	public static void tearDown() {
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	private PlaceOrderResp placeOrder(int userId, String productId) {

		PlaceOrderReq placeOrderReq = PlaceOrderService
				.getDefaultOrderReq(userId);

		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);

		if (productId != null) {
			orderItemVo.setProductId(productId);
		}

		return PlaceOrderService.callPlaceOrderService(placeOrderReq);

	}

	private int registerUser() throws Exception {

		return (Integer) new OrderCallService().registerUser().get("userId");

	}

	private void verify(int userId) {
		FirstPaidOrder expect = getFirstPaidOrderFromMssql(userId);
		FirstPaidOrder actual = getFirstPaidOrderFromMongo(userId);
		if (expect == null) {
			DataUtil.verify(null, actual,
					String.format("验证买家id为%d的首单信息 == null", userId));
		} else {
			DataUtil.verifyObject(expect, actual,
					String.format("验证买家id为%d的首单信息", userId));
		}
	}

	@SuppressWarnings("rawtypes")
	public FirstPaidOrder getFirstPaidOrderFromMssql(int userId) {
		FirstPaidOrder firstOrder = null;
		String sql = String
				.format("SELECT top 1 iOrderId as orderId,dPaidTime as paidTime,iUserId as id FROM ymt_orders(nolock) WHERE iuserid = %d and dPaidTime is not NULL ORDER BY dPaidTime ASC",
						userId);
		List<Map> list = new DefaultWapper().executeSql(sql);

		if (!DataUtil.isNullOrEmpty(list)) {

			firstOrder = new FirstPaidOrder();
			firstOrder.setId(Long.valueOf(list.get(0).get("id").toString()));

			if (null != list.get(0).get("paidTime")) {
				firstOrder.setPaidTime(YMTDateUtil.getDate(
						list.get(0).get("paidTime").toString(),
						YMTDateUtil.YMDHMSS));
			}
		}
		return firstOrder;
	}

	public FirstPaidOrder getFirstPaidOrderFromMongo(Integer userId) {
		return new UserAnalysisMongoWapper().findById(userId);

	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_ChangeBuyerFirstOrder_001() {
		Logger.start(true, "无订单的新用户在mongo的首单表中没有记录");
		try {

			int userId = registerUser();

			verify(userId);
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_ChangeBuyerFirstOrder_002() {
		Logger.start(true, "新用户下了一笔创建状态的订单后，在mongo的首单表中没有记录");
		try {

			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			int userId = registerUser();

			OrderCreate order = new OrderCreate();

			Integer orderId = order.create1_M2cOrder(userId, sellerId)
					.getiOrderId();

			SyncVerifyService.getSyncResult(orderId);

			verify(userId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_ChangeBuyerFirstOrder_003() {
		Logger.start(true,
				"老用户有多笔已支付状态的订单，但在mongo的首单表中没有记录，再次支付后，会同步首单记录到mongo的首单表中");
		try {
			OrderCreate order = new OrderCreate();
			OrderCallService orderCallService = new OrderCallService();
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			int userId = registerUser();

			SyncVerifyService.getSyncResult(order.create2_PayOrder(userId,
					sellerId).getiOrderId());
			SyncVerifyService.getSyncResult(order.create2_PayOrder(userId,
					sellerId).getiOrderId());

			//Thread.sleep(5000);

			new UserAnalysisMongoWapper().removeBuyerOrder(userId);

			Integer orderId = order.create2_PayOrder(userId, sellerId)
					.getiOrderId();
			SyncVerifyService.getSyncResult(orderId);

			verify(userId);
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_ChangeBuyerFirstOrder_004() {
		Logger.start(true,
				"老用户有多笔已支付状态的订单，且在mongo的首单表中有记录，再次支付后，mongo的首单表中该用户的记录不变");
		try {
			OrderCreate order = new OrderCreate();
			OrderCallService orderCallService = new OrderCallService();
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			int userId = registerUser();

			SyncVerifyService.getSyncResult(order.create2_PayOrder(userId,
					sellerId).getiOrderId());

			SyncVerifyService.getSyncResult(order.create2_PayOrder(userId,
					sellerId).getiOrderId());

			new UserAnalysisMongoWapper().removeBuyerOrder(userId);

			Integer orderId = order.create2_PayOrder(userId, sellerId)
					.getiOrderId();
			SyncVerifyService.getSyncResult(orderId);

			verify(userId);
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	// 查询用户首次支付订单，排除虚拟商品
	public void Tc_ChangeBuyerFirstOrder_005() {
		Logger.start(true, "新用户下了一笔虚拟商品创建订单，在mongo的首单表中没有记录");
		try {

			int userId = registerUser();

			//虚拟商品
			String productId = "aaaaa-bbbbb-ccccc-ddddd";

			placeOrder(userId, productId);

			Thread.sleep(3000);

			verify(userId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_ChangeBuyerFirstOrder_006() {
		Logger.start(true, "新用户下了一笔虚拟商品创建订单,在mongo的首单表中没有记录");
		try {

			int userId = registerUser();

			String productId = "aaaaa-bbbbb-ccccc-ddddd";

			PlaceOrderResp placeOrderResp = placeOrder(userId, productId);

			int tradingId = placeOrderResp.getTradingId();

			BigDecimal price = placeOrderResp.getPayAmount();

			new OrderCallService().orderPayRequest(userId, price, tradingId);

			Thread.sleep(3000);

			verify(userId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_ChangeBuyerFirstOrder_007() {
		Logger.start(true, "新用户下了一笔虚拟商品,第二笔非虚拟商品");
		try {

			int userId = registerUser();

			String productId = "aaaaa-bbbbb-ccccc-ddddd";

			PlaceOrderResp placeOrderResp = placeOrder(userId, productId);

			int tradingId = placeOrderResp.getTradingId();

			BigDecimal price = placeOrderResp.getPayAmount();

			new OrderCallService().orderPayRequest(userId, price, tradingId);

			placeOrderResp = placeOrder(userId, null);

			tradingId = placeOrderResp.getTradingId();

			price = placeOrderResp.getPayAmount();

			new OrderCallService().orderPayRequest(userId, price, tradingId);

			Thread.sleep(3000);

			verify(userId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}